import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_ios/store_kit_wrappers.dart';
import 'package:in_app_purchase_ios/in_app_purchase_ios.dart';

import '../../config/net/api.dart';
import '../loding.dart';
import '../log_utils.dart';
import '../network_utils.dart';

class IOSPayment {
  // static final String sku = 'com.xdan.xdanflutter';
  /// 单例模式
  static final IOSPayment _iosPaymented = IOSPayment._internal();
  // iOS订阅监听
  StreamSubscription<List<PurchaseDetails>>? subscription;

  /// 判断是否可以使用支付
  Future<bool> isAvailable() async => await purchaseConnection.isAvailable();

  bool payStatus = true;

  factory IOSPayment() {
    return _iosPaymented;
  }

  // 通过私有方法_internal()隐藏了构造方法，防止被误创建
  IOSPayment._internal() {
    // 初始化
    init();
  }

  void init() async {}

  // 应用内支付实例
  InAppPurchase purchaseConnection = InAppPurchase.instance;
  FlutterSecureStorage storage = const FlutterSecureStorage();

  // 开始订阅
  void startSubscription() async {
    if (subscription != null) return;
    LogUtilTool.println('>>> start subscription');
    // 支付消息订阅
    Stream<List<PurchaseDetails>> purchaseUpdates = purchaseConnection.purchaseStream;
    subscription = purchaseUpdates.listen((purchaseDetailsList) {
      // ignore: avoid_function_literals_in_foreach_calls
      purchaseDetailsList.forEach((PurchaseDetails purchaseDetails1) async {
        if (purchaseDetails1 is AppStorePurchaseDetails) {
          AppStorePurchaseDetails purchaseDetails = purchaseDetails1;
          LogUtilTool.println(
              'purchaseDetails.status = ${purchaseDetails.status} applicationUsername = ${purchaseDetails.skPaymentTransaction.payment.applicationUsername}-- productID = ${purchaseDetails.productID}, purchaseID = ${purchaseDetails.purchaseID} serverVerificationData = ${purchaseDetails.verificationData.serverVerificationData}');
          LogUtilTool.println('>>> purchased3');
          if (purchaseDetails.status == PurchaseStatus.pending) {  //购买中
            LogUtilTool.println('>>> pending');
            payStatus = false;

            // 业务代码略：有订单开始支付，向外部发出通知，并记录到缓存中；
          } else {
            if (purchaseDetails.status == PurchaseStatus.error) {
              LogUtilTool.println('>>> error');
              // 业务代码略：有订单支付错误，向外部发出通知
              // 下面是删除
              // String? value = await storage.read(key: purchaseDetails.productID);
              // String orderId = value!.split('￥')[0];
              // writeStorage(purchaseDetails.productID, orderId, 'cancel');
              finalTransaction(purchaseDetails);

            } else if (purchaseDetails.status == PurchaseStatus.purchased) {  //购买成功
              LogUtilTool.println('>>> purchased');
              if (purchaseDetails.purchaseID != null) {
                String? orderId = purchaseDetails.skPaymentTransaction.payment.applicationUsername;
                if (orderId == null || orderId.isEmpty) {
                  // 如果applicationUsername为空，则在存储里面查找
                  orderId = await foundRecentOrder(purchaseDetails.productID);
                }
                if (orderId.isEmpty) {
                  // 找不到订单id,结束
                  finalTransaction(purchaseDetails);
                  print('iOS 支付,找不到订单id');
                  Loading.hideLoading();
                  return;
                }
                //  支付成功，向外部发出通知
                //  开始核验订单，核验结果由外部监听
                LogUtilTool.println(
                    '支付完成 -- ${purchaseDetails.productID},${purchaseDetails.purchaseID}');
                // Api.payV2AppleVerity(appleProductId: purchaseDetails.productID ?? "", orderNo: orderId, receiptData: purchaseDetails.verificationData.serverVerificationData).then((value) async {
                //   Loading.hideLoading();
                //   if (value.success) {
                //     didFinished();
                //     Future.delayed(const Duration(milliseconds: 1500), () {
                //       final logic = Get.find<GoldCoinLogic>();
                //       //更新用户金币信息
                //       logic.getAccountInfo();
                //     });
                //   } else {
                //     ConnectivityResult value = await NetworkUtils.getNetworkType();
                //     if (value == ConnectivityResult.wifi || value == ConnectivityResult.mobile) {
                //       payV2AppleVerity(appleProductId: purchaseDetails.productID ?? "", receiptData: purchaseDetails.verificationData.serverVerificationData, orderNo: orderId!);
                //     }
                //   }
                //   payStatus = true;
                // });
              }
            }
          }
        }
      });
    }, onDone: () {
      // subscription?.cancel();
      Loading.hideLoading();
      LogUtilTool.println('支付完成2');
      payStatus = true;
      xdShowToast('支付失败，请重试');
    }, onError: (error) {
      Loading.hideLoading();
      payStatus = true;
      xdShowToast('支付失败，请重试');
      // handle error here.
    });
  }

  /// 启动支付
  void iosPay(String orderId, String commodityID,
      {required Function(String err) onError}) async {
    // ignore: await_only_futures
    // DeviceInfo().sp.setString('iosPay',orderId);
    // 获取商品详情信息
    ProductDetailsResponse appStoreProducts =
    // ignore: prefer_collection_literals
    await purchaseConnection.queryProductDetails([commodityID].toSet());
    if (appStoreProducts.productDetails.isEmpty) {
      //获取商品列表失败
      Loading.hideLoading();
      xdShowToast('支付失败，请重试');
      return;
    }

    // purchaseConnection.
    // 发起支付
    print('purchaseConnection orderId: $orderId');
    purchaseConnection
        .buyConsumable(
        purchaseParam: PurchaseParam(
          productDetails: appStoreProducts.productDetails.first,
          applicationUserName: orderId,
        ))
        .then((value) {
      if (value) {
      // 只要能发起，就写入
      writeStorage(commodityID, orderId, 'pending');
    }
  }).catchError((err) async {
      onError.call('当前商品您有未完成的交易，请等待iOS系统核验后再次发起购买。');
      // ProgressDialog.dismiss(model!.context);
      // lyShowToast('支付错误请稍后重试');
      LogUtilTool.println('支付回调 ---- 1');
      await didFinished();
      iosPay(orderId, commodityID, onError: (String err) {});
    });
  }

  //存储
  writeStorage(String key, String orderId, String status) {
    storage.write(key: key, value: '$orderId￥$status');
  }

  // 查找订单id
  Future<String> foundRecentOrder(String sku) async {
    String orderId = '';
    String? values = await storage.read(key: sku);

    if (values != null) {
      orderId = values.split('￥')[0];
    }
    return orderId;
  }

  didFinished() async {
    //结束上一次购买事物
    var paymentWrapper = SKPaymentQueueWrapper();
    var transactions = await paymentWrapper.transactions();
    LogUtilTool.println("wztest  initStoreInfo transaction.length${transactions.length}");
    // ignore: avoid_function_literals_in_foreach_calls
    for (var transaction in transactions)  {
      await paymentWrapper.finishTransaction(transaction);
    }
  }

  // 关闭交易
  void finalTransaction(PurchaseDetails purchaseDetails) async {
    LogUtilTool.println(
        '删除 -- ${purchaseDetails.productID},${purchaseDetails.purchaseID}');
    Loading.hideLoading();
    await Future.delayed(const Duration(milliseconds: 200));
    xdShowToast("支付取消");
    await purchaseConnection.completePurchase(purchaseDetails);
    // 每完成一张订单进行缓存的清除
    if (!await checkStorage()) {
      storage.delete(key: purchaseDetails.productID);
      // stopListen();
    }
    payStatus = true;
  }

  // 校验是否还有缓存
  Future<bool> checkStorage() async {
    Map<String, String> remainingValues = await storage.readAll();
    return remainingValues.isNotEmpty;
  }

  // 关闭监听
  stopListen() async {
    subscription?.cancel();
    subscription = null;
  }
}

///未验证订单验证
void payV2AppleVerity({required String appleProductId, required String receiptData, required String orderNo}) {
  // Api.payV2AppleVerity(appleProductId: appleProductId, receiptData: receiptData, orderNo: orderNo).then((value) {
  //   if (value.success) {
  //     IOSPayment().didFinished();
  //     final logic = Get.find<GoldCoinLogic>();
  //     //更新用户金币信息
  //     logic.getAccountInfo();
  //   }
  // });
}

// appleRechargeAgain(data,String transactionId) {
//   var orderId = DeviceInfo().sp.getString('iosPay')??"";
//   LogUtilTool.println('订单数据1 ----- orderId=$orderId');
//   if (orderId.isNotEmpty) {
//     LogUtilTool.println('订单数据2 ----- orderId=$orderId');
//     Api().appleRechargeVerifyConfirm(orderId,transactionId, data)
//         .then((value) async {
//       if (value == true) {
//         IOSPayment().payStatus = true;
//         DeviceInfo().sp.remove('iosPay');
//         if (IOSPayment().model != null) {
//           IOSPayment().model!.getByUserId();
//         }
//       }else{
//         DeviceInfo().sp.remove('iosPay');
//       }
//     });
//   }
// }